/*
 * @Author: spycym
 * @Date: 2022-11-15 22:21:45
 * @LastEditTime: 2022-11-17 22:06:23
 * @LastEditors: spycym
 * @Description: 
 * 不要随便动我的代码哟!
 */
import { defineStore } from 'pinia'
import { reactive, computed } from 'vue'
import { nanoid } from 'nanoid'
type todo = {
  id: string,
  name: string,
  done: boolean,
  isEdit: boolean
}
export const useTodoStore = defineStore("Todo", () => {
  let todos = reactive<todo[]>([
    { id: '001', name: '学习', done: false, isEdit: false },
    { id: '002', name: '吃饭', done: true, isEdit: false },
    { id: '003', name: '睡觉', done: false, isEdit: false }
  ])
  let already = computed(() => todos.filter(item => item.done).length)
  let all = computed(() => todos.length)
  function addTodoObj(TodoName: string) {
    const obj: todo = { id: nanoid(), name: TodoName, done: false, isEdit: false }
    todos.unshift(obj)
  }
  function editDone(todoId: string) {
    todos.forEach(item => {
      if (todoId === item.id) {
        item.done = !item.done
      }
    })
  }
  function editChange(todoId: string) {
    todos.forEach(item => {
      if (todoId === item.id) {
        item.isEdit = !item.isEdit
      }
    })
  }
  function editName(newName: string, todoId: string) {
    editChange(todoId)
    todos.forEach(item => {
      if (todoId === item.id) {
        item.name = newName
      }
    })
  }
  function deleteTodoObj(todoObj: todo) {
    const index = todos.indexOf(todoObj)
    todos.splice(index, 1)
  }
  function isAll(todoDone: boolean) {
    todos.map(item => {
      item.done = todoDone
      return item
    })
  }
  return {
    todos,
    addTodoObj,
    editDone,
    editChange,
    editName,
    deleteTodoObj,
    already,
    all,
    isAll
  }
})
